using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Project.Domain.AggregatesModel;
using Project.Domain.SeedWork;

namespace Project.Infrastructure.Repositorys
{
    public class ProjectRepository:IProjectRepository
    {
        private readonly ProjectContext _dbContext;
        public ProjectRepository(ProjectContext projectContext)
        {
            _dbContext = projectContext;
        }

        public IUnitOfWork UnitOfWork => _dbContext;
        
        public async Task<Domain.AggregatesModel.Project> GetAsync(int id)
        {
            var project = await _dbContext.Projects
                .Include(p => p.Properties)
                .Include(p => p.Viewers)
                .Include(a => a.Contributors)
                .Include(a => a.VisibleRule)
                .SingleOrDefaultAsync(b => b.Id == id);
            return project;
        }

        public Domain.AggregatesModel.Project Add(Domain.AggregatesModel.Project project)
        {
            if(project.IsTransient())
            {
                return _dbContext.Add(project).Entity;
            }
            return project;
        }

        public void Update(Domain.AggregatesModel.Project project)
        {
            _dbContext.Projects.Update(project);
        }
    }
}